﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KC.DataAccess.MV;

namespace KC.Presentation.Mv8CMS
{
	public partial class ReferrerPeeker : Form
	{
		public ReferrerPeeker()
		{
			InitializeComponent();
		}

		private void ReferrerPeeker_Load(object sender, EventArgs e)
		{
			DataTable dt = KC.DataAccess.MV.Utils.GetMonthlySessions();
			foreach (DataRow dr in dt.Rows)
			{
				DateTime
					startDay = DateTime.Parse(dr[0].ToString().Split('-')[1] + "/01/" + dr[0].ToString().Split('-')[0]),
					endDay = startDay.AddMonths(1).AddSeconds(-1);
				int Hits = int.Parse(dr[1].ToString());
				dynamic obj = new {
					startday = startDay,
					stopday = endDay,
					Sessions = Hits,
					text = startDay.ToString("MMMM yyyy") + "  (" + Hits.ToString("###,###,###") + ")",
				};
				lbMonths.Items.Add(obj);
			}
		}

		private void lbMonths_SelectedIndexChanged(object sender, EventArgs e)
		{
			UpdateGrid();
		}

		private void UpdateGrid()
		{
			if (lbMonths.SelectedItems.Count == 0) return;
			dynamic obj = (dynamic)lbMonths.SelectedItem;
			IQueryable<Activity> result = KC.DataAccess.MV.Utils.GetActivitiesByTimes(obj.startday, obj.stopday);

			List<dynamic> result2 = new List<dynamic>();
			foreach (Activity act in result.AsEnumerable<Activity>())
			{
				string query, engine;
				bool isSearchEngineReferral = KC.Business.Web.RequestTools.isSearchEngineReferral(new Uri(act.Referrer), out engine, out query);
				dynamic obj2 = new
				{
					ID = act.ID,
					IP = act.Session.IP.Address,
					Referrer = act.Referrer,
					Query = isSearchEngineReferral ? query : ""
				};
				if (!cbQueriesOnly.Checked || (cbQueriesOnly.Checked && isSearchEngineReferral))
					result2.Add(obj2);
			}
			dgReferrers.DataSource = result2;
		}

		private void dgReferrers_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			switch (e.ColumnIndex)
			{
				case 0: // Activity ID ("ID")
					break;
				case 1: // IP
					break;
				case 2: // Referrer
				case 3: // Query
					if (string.IsNullOrEmpty((string)dgReferrers.Rows[e.RowIndex].Cells[2].Value)) return;
					string text = (string)dgReferrers.Rows[e.RowIndex].Cells[2].Value;
					string target = "";
					if (!text.ToLower().Contains("http://")) target = "http://www.kconnolly.net";
					if (!text.ToLower().Contains("http://") && !text.Trim().StartsWith("/")) target += "/";
					if (text.Trim().StartsWith("/")) target = "http://www.kconnolly.net";
					target += text;
					System.Diagnostics.Process.Start(target);
					

					break;
			}
		}

		private void cbQueriesOnly_CheckedChanged(object sender, EventArgs e)
		{
			UpdateGrid();

		}
	}
}
